<?php

namespace App\Http\Controllers\v1;


use App\Models\Area;
use App\Models\Family;
use App\Models\Org;
use App\Models\User;
use App\Models\Volunteer;
use Illuminate\Http\Request;
use App\Libs\IdCard;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Hashids\Hashids;

class FamilyController extends Controller
{

    public function create(Request $request)
    {
        $rules = ['real_name' => 'required',  'id_number'=>'required', 'nation'=>'required' , 'province_id'=>'required|exists:area,id', 'city_id'=>'required|exists:area,id', 'county_id'=>'required|exists:area,id','addr'=>'required|string', 'pwd'=>'required','relation'=>'required',];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }

        if(!preg_match('/^[a-zA-Z0-9]+$/u', $request->input('pwd')) || strlen($request->input('pwd')) < 6 || strlen($request->input('pwd')) > 20)
        {
            $this->setStatus(10001);
            $this->setMsg('密码只能由数字或者字母组成,长度在6~20字符');
            return $this->response();
        }
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        if(empty($userInfo->volunteer->family_id))
        {
            $newFamily = new Family();
            $newFamily->user_id = $userInfo->id;
            $newFamily->username = $userInfo->username;
            $newFamily->save();

            $userInfo->volunteer->family_id = $newFamily->id;
            $userInfo->volunteer->relation = '户主';
            $userInfo->volunteer->join_family_time = date('Y-m-d H:i:s');
            $userInfo->volunteer->save();
        }

        if($userInfo->volunteer->relation != '户主')
        {
            $this->setStatus(10001);
            $this->setMsg('只有户主才能添加成员');
            return $this->response();
        }

        $familyCount = Volunteer::where('family_id', $userInfo->volunteer->family_id)->count();

        if($familyCount >= 8)
        {
            $this->setStatus(10001);
            $this->setMsg('家庭成员最多只能有8名成员');
            return $this->response();
        }

        $check = Volunteer::where('id_number', $request->get('id_number'))->where('org_id', $this->getOrdId())->first();

        if(!empty($check))
        {
            $this->setStatus(10001);
            $this->setMsg('身份证号已经被其他账号使用!');
            return $this->response();
        }
        DB::beginTransaction();
        try{
            $member = new User();
            $data['username'] = $request->get('id_number');
            $data['type'] = 1;
            $data['org_id'] = $this->getOrdId();
            $data['pwd'] = Hash::make($request->input('pwd'));
            $data['avatars'] = $request->input('avatars', '');
            $data['token'] = User::createToken();
            $member->fill($data)->save();

            $tmp = array_only(Input::all(), ['id_number', 'real_name', 'nation', 'province_id', 'city_id', 'county_id', 'addr', 'relation']);
            $area = Area::getList([$tmp['province_id'], $tmp['city_id'], $tmp['county_id']]);
            $tmp['province_name'] = $area[$tmp['province_id']]['name'];
            $tmp['city_name'] = $area[$tmp['city_id']]['name'];
            $tmp['county_name'] = $area[$tmp['county_id']]['name'];

            $volunteer = new Volunteer();
            $volunteer->fill($tmp);
            $volunteer->org_id = $member->org_id;
            $volunteer->user_id = $member->id;
            $volunteer->family_id = $userInfo->volunteer->family_id;
            $volunteer->identifier = 'V'.date('ymd').sprintf('%06d', $member->id);
            $volunteer->join_family_time = date('Y-m-d H:i:s');
            $volunteer->save();

            DB::table('user_score_item')->insert(['user_id'=>$member->id, 'type'=>0, 'score'=>Org::getScoreConf()['register'], 'remark'=>'注册奖励']);
            Log::info('SCORE 注册奖励积分 userId:'.$member->id.'  score:'.Org::getScoreConf()['register']);


            $format = $member->getAllInfo();
            $format['token'] = $member->token;
            DB::commit();

            $this->setData($format);
            return $this->response();

        }catch (\Exception $e)
        {
            DB::rollBack();

            $this->setStatus(-10001);
            $this->setMsg('服务器忙,请稍后重试'.$e->getMessage());
            return $this->response();
        }

    }

    public function bind(Request $request)
    {
        $rules = ['phone' => 'required',  'pwd'=>'required', 'relation'=>'required',];
        $validator = Validator::make(Input::all(), $rules);
        if($validator->fails())
        {
            $errors = $validator->errors();
            $this->setStatus(10001);
            $this->setMsg(implode(' ', $errors->all()));

            return $this->response();
        }

        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        if(empty($userInfo->volunteer->family_id))
        {
            $newFamily = new Family();
            $newFamily->user_id = $userInfo->id;
            $newFamily->username = $userInfo->username;
            $newFamily->save();

            $userInfo->volunteer->family_id = $newFamily->id;
            $userInfo->volunteer->relation = '户主';
            $userInfo->volunteer->join_family_time = date('Y-m-d H:i:s');
            $userInfo->volunteer->save();
        }

        if($userInfo->volunteer->relation != '户主')
        {
            $this->setStatus(10001);
            $this->setMsg('只有户主才能添加成员');
            return $this->response();
        }

        $familyCount = Volunteer::where('family_id', $userInfo->volunteer->family_id)->count();

        if($familyCount >= 8)
        {
            $this->setStatus(10001);
            $this->setMsg('家庭成员最多只能有8名成员');
            return $this->response();
        }

        $phone = $request->input('phone');
        $pwd = $request->input('pwd');
        $type = 1;
        $volunteer = Volunteer::where('org_id', $this->getOrdId())->where('id_number', $phone)->first();
        if(empty($volunteer))
        {
            $bind = User::where(function($query) use ($phone){
                $query->where('username', $phone)->orwhere('phone', $phone);
            })->where('type', $type)->where('org_id', $this->getOrdId())->first();
        }else{
            $bind = User::where(function($query) use ($phone, $volunteer){
                $query->where('username', $phone)->orwhere('phone', $phone)->orwhere('id', $volunteer->user_id);
            })->where('type', $type)->where('org_id', $this->getOrdId())->first();
        }

        //密码错误
        if(empty($bind) || !Hash::check($pwd, $bind->pwd))
        {
            $this->setStatus(10001);
            $this->setMsg('用户名或密码错误');
            return $this->response();
        }

        if($bind->volunteer->family_id > 0)
        {
            $this->setStatus(10001);
            $this->setMsg('该用户已在其它家庭中，不能重复绑定');
            return $this->response();
        }

        $bind->volunteer->family_id = $userInfo->volunteer->family_id;
        $bind->volunteer->relation = $request->get('relation');
        $bind->volunteer->join_family_time = date('Y-m-d H:i:s');
        $bind->volunteer->save();

        return $this->response();
    }

    public function listInfo(Request $request)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        if(empty($userInfo->volunteer->family_id))
        {
            $data['family_size'] = 0;
            $data['reward_time'] = 0;
            $data['family'] = [];
            $this->setData($data);
            return $this->response();
        }
        $nodes = User::with('volunteer');
        $userIds = Volunteer::selectRaw('group_concat(user_id) as ids')->where('family_id', $userInfo->volunteer->family_id)->where('user_id', '!=', $userInfo->id)->first();
        if(empty($userIds->ids))
        {
            $nodes = $nodes->whereRaw("id in (0)");
        }else{
            $nodes = $nodes->whereRaw("id in ({$userIds->ids})");
        }

        $nodes = $nodes->orderBy('id');
        $nodes = $nodes->get();

        $data = [];
        $data['family_size'] = count($nodes);
        $data['reward_time'] = 0;
        foreach($nodes as $node)
        {
            $data['reward_time'] += $node->volunteer->reward_time;
            $data['family'][] = $node->getAllInfo();

        }

        $this->setData($data);
        return $this->response();
    }

    public function info(Request $request,  $id)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        $memberInfo = User::where('id', $id)->first();

        if($userInfo->volunteer->family_id != $memberInfo->volunteer->family_id)
        {
            $this->setStatus(10001);
            $this->setMsg('非法id');

            return $this->response();
        }

        $data = $memberInfo->getAllInfo();

        $this->setData($data);
        return $this->response();
    }

    public function delete(Request $request,  $id)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        $memberInfo = User::where('id', $id)->first();

        if($userInfo->volunteer->family_id != $memberInfo->volunteer->family_id)
        {
            $this->setStatus(10001);
            $this->setMsg('非法id');

            return $this->response();
        }

        $volunteer = Volunteer::where('user_id', $memberInfo->id)->first();
        $volunteer->fill(['family_id'=>0, 'relation'=>'']);
        $volunteer->save();

        $count = Volunteer::where('family_id', $userInfo->volunteer->family_id)->count();

        //家庭成员都被删除，删除家庭
        if($count == 1)
        {
            Family::where('id', $userInfo->volunteer->family_id)->delete();

            $userInfo->volunteer->fill(['family_id'=>0, 'relation'=>''])->save();
        }

        return $this->response();
    }

    public function edit(Request $request, $id)
    {
        $userInfo = User::where('type', 1)->where('token', $this->getToken())->first();

        $memberInfo = User::where('id', $id)->first();

        if($userInfo->volunteer->family_id != $memberInfo->volunteer->family_id)
        {
            $this->setStatus(10001);
            $this->setMsg('非法id');

            return $this->response();
        }

        $data = array_only($request->all(), ['pwd', 'relation']);

        if(isset($data['pwd']))
        {
            $data['pwd'] = Hash::make($request->input('pwd'));
        }

        $memberInfo->volunteer->fill($data)->save();

        return $this->response();
    }

}
